package cn.edu.cqu.bysj.services.hibernate;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.cqu.bysj.domains.StaticStationInfo;
import cn.edu.cqu.bysj.services.StaticStationInfoCRUD;

@Service("StaticStationInfoCRUDHibernate")
public class StaticStationInfoCRUDHibernate implements StaticStationInfoCRUD {

	private HibernateTemplate ht;
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		ht = new HibernateTemplate(sessionFactory);
	}
	
	@Override
	@Transactional
	public void add(StaticStationInfo staticStationInfo) {
		ht.save(staticStationInfo);
	}

	@Override
	public StaticStationInfo getByName(String stationName) {
		return ht.get(StaticStationInfo.class, stationName);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<StaticStationInfo> getAll() {
		List<StaticStationInfo> infos = (List<StaticStationInfo>) ht.find("from StaticStationInfo");
		return infos;
	}

	@Transactional
	@Override
	public void edit(String name,StaticStationInfo staticStationInfo) {
		StaticStationInfo ssi = this.getByName(name);
		ssi.setJianpinName(staticStationInfo.getJianpinName());
		ssi.setNum(staticStationInfo.getNum());
		ssi.setQuanpinName(staticStationInfo.getQuanpinName());
		ssi.setStationCode(staticStationInfo.getStationCode());
		ssi.setStationName(staticStationInfo.getStationName());
		ssi.setbLat(staticStationInfo.getbLat());
		ssi.setbLong(staticStationInfo.getbLong());
		ht.update(ssi);
	}

	@Transactional
	@Override
	public void deleteByName(String name) {
		StaticStationInfo info = this.getByName(name);
		ht.delete(info);
	}
	
	@Override
	@Transactional
	public void deleteAll()
	{
		List<StaticStationInfo> infos = this.getAll();
		for (StaticStationInfo staticStationInfo : infos) {
			this.deleteByName(staticStationInfo.getName());
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public StaticStationInfo getByCode(String code)
	{
		String sql = "from StaticStationInfo s where s.stationCode=?";
		List<StaticStationInfo> ssis = (List<StaticStationInfo>) ht.find(sql, new Object[]{code});
		if (ssis.size() == 0)
			return null;
		return ssis.get(0);
	}

}
